package exercise;

public class VolatileTest {

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(new MyThread());
        t1.setName("改变i值的线程");
        t1.start();
        for(int i=1; i<=1000; i++){
            Thread t2 = new Thread(new MyThread2());
            t2.setName("获取i值的线程"+i+":");
            t2.start();
        }
    }

}

class MyThread implements Runnable{

    private static Bean b = Bean.getBean();
    
    @Override
    public void run() {
        System.out.println("当前线程:"+Thread.currentThread().getName());
        for(int i=1;i<=1000;i++){
            System.out.println(Thread.currentThread().getName()+",第"+i+"次,前:"+b.getI());
            b.setI(b.getI()+1);
            System.out.println(Thread.currentThread().getName()+",第"+i+"次,后:"+b.getI());
            try {
                Thread.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("线程:"+Thread.currentThread().getName()+"结束!!");
    }
    
}
    
class MyThread2 implements Runnable{

    private static Bean b = Bean.getBean();
    
    @Override
    public void run() {
        try {
            Thread.sleep(2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("当前线程:"+Thread.currentThread().getName()+"值:"+b.getI());
        System.out.println("线程:"+Thread.currentThread().getName()+"结束");
    }
    
}

